package com.linxin.ai_automates_periodontal_treatment_system.interceptor;

// TokenInterceptor.java

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.linxin.ai_automates_periodontal_treatment_system.common.Result;
import com.linxin.ai_automates_periodontal_treatment_system.entity.Doctor;
import com.linxin.ai_automates_periodontal_treatment_system.service.DoctorService;

import com.linxin.ai_automates_periodontal_treatment_system.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    private final DoctorService doctorService;

    @Autowired
    public TokenInterceptor(DoctorService doctorService) {
        this.doctorService = doctorService;
//         log.info("doctorService = {}", doctorService);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login") || requestURI.contains("register")) {
            return true; // 如果URI中包含"login"，直接返回true，不对登录页做处理
        }

        String token = request.getHeader("Authorization"); // 假设token存储在Authorization header中
//         log.info("拦截器拦截的 token = {}", token);
        if (token == null || token.isEmpty()) {
            // 如果token为空，返回错误信息，并拒绝访问
            response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
            return false;
        }

        // 从token中获取username
        String account = JwtUtil.getAccountFromToken(token);
//        log.info("拦截器拦截的 username = {}", account);

        // 根据用户名在数据库中查询用户信息
        LambdaQueryWrapper<Doctor> queryWrapper = new QueryWrapper<Doctor>().lambda().eq(Doctor::getAccount, account);
        Doctor doctor = doctorService.getOne(queryWrapper);
        // log.info("拦截器拦截的 user = {}", user);
        if (doctor == null) {
            // 如果用户不存在，返回错误信息，并拒绝访问
            response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
            return false;
        }

        // 如果用户存在，放行, 将用户id设置到request中
        request.setAttribute("doctorId", doctor.getId());
        return true;
    }
}



